package com.zls.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zls.mapper.SysUserMapper;
import com.zls.page.PageResult;
import com.zls.page.QueryPageBean;
import com.zls.pojo.SysUser;
import com.zls.service.SysUserService;
import lombok.ToString;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageResult pageResult = new PageResult();
        Integer currentPage = queryPageBean.getCurrentPage();//当前页
        Integer pageSize = queryPageBean.getPageSize();//每页大小
        String queryString = queryPageBean.getQueryString();//查询条件
        //total总记录数
        List<SysUser> page = sysUserMapper.findPage((currentPage - 1) * pageSize, pageSize,queryString);
        //rows  当前页的数据
        Long count = sysUserMapper.count(queryString);
        pageResult.setRows(page);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    @Transactional
    public int addSysUser(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        /**
         * 随机生成32位盐值
         */
        String salt = RandomStringUtils.randomAlphanumeric(32);
        sysUser.setSalt(salt);
        /**
         * 使用sha256Hash加密密码
         */
        sysUser.setPassword(new Sha256Hash(sysUser.getPassword(),salt).toHex());
        System.out.println("用户加密后的密码:"+sysUser.getPassword());
        /**
         * 将加密后数据放入数据库
         */
        int insert = sysUserMapper.insert(sysUser);
        return insert;
    }

    @Override
    @Transactional
    public int editSysUser(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());
        /**
         * 随机生成32位盐值
         */
        String salt = RandomStringUtils.randomAlphanumeric(32);
        sysUser.setSalt(salt);
        /**
         * 使用sha256Hash加密密码
         */
        sysUser.setPassword(new Sha256Hash(sysUser.getPassword(),salt).toHex());
        System.out.println("用户加密后的密码:"+sysUser.getPassword());
        /**
         * 将加密后数据放入数据库
         */
        int i = sysUserMapper.updateById(sysUser);
        return i;
    }

    @Override
    public int delete(int id) {
        int i=sysUserMapper.deleteId(id);
        return i;
    }
}
